package org.cu.ooad.finalproject.layar;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Logger;

import com.google.appengine.repackaged.org.json.JSONArray;
import com.google.appengine.repackaged.org.json.JSONObject;

public class GoogleImageSearch extends ImageSearchBehavior {
	
	private final static Logger log = Logger.getLogger(GoogleImageSearch.class.getName());

	@Override
	public String getImageURL(String search) {
		search.replaceAll(" ", "%20");

		try {
			URL url = new URL(
					"https://ajax.googleapis.com/ajax/services/search/"
							+ "images?v=1.0&q="+search);
			URLConnection connection = url.openConnection();
			connection.addRequestProperty("Referer", "http://cucampusmaplayer"
					+ ".appspot.com");

			String line;
			StringBuilder builder = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

			JSONObject json = new JSONObject(builder.toString());

			JSONObject responseData = json.getJSONObject("responseData");
			
			JSONArray results = responseData.getJSONArray("results");
			if (results.length()>0) {
				JSONObject imageObject = (JSONObject) results.get(0);
				return imageObject.get("url").toString();
			}

		} catch (Throwable t) {
			log.warning("Error while obtaining image: "+t.getMessage());
		}

		return "";
	}
}
